package com.gs.wzweather.schedual;


import com.gs.wzweather.entity.SmsThreshold;
import com.gs.wzweather.service.SmsWarningService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Legolas
 * Date: 2017/11/23 0023
 */
@Service
@EnableScheduling
public class SmsWarningSchedual {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    HashSet warningSet = new HashSet();

    @Autowired
    SmsWarningService smsWarningService;

    public void test(){
        smsWarningService.getSmsThresholds();
    }

    @Scheduled(cron="0 0/5 *  * * ?")//每5分钟运行一次
    public void ListenStatistics(){
        System.out.println(warningSet);

        List<SmsThreshold> thresholds = smsWarningService.getSmsThresholds();
        String content="";

        for (int i=0;i<thresholds.size();i++){
            SmsThreshold smsThreshold = thresholds.get(i);
            if (!smsThreshold.isLocked()){
                if(smsThreshold.getName().contains("降水")){
                    String statistic = smsWarningService.getStatistics(smsThreshold.getStation(),smsThreshold.getParam());

                    logger.info("statistic->{}",statistic);

                    if (Double.parseDouble(statistic)>Double.parseDouble(smsThreshold.getThreshold())&&!warningSet.contains(smsThreshold.getId())){
                        content+=smsThreshold.getStationName()+smsThreshold.getName()+"数值"+statistic+"，超出阈值"+smsThreshold.getThreshold()+"。";

                        warningSet.add(smsThreshold.getId());
                    }
                }
                if(smsThreshold.getName().contains("最大风")||smsThreshold.getName().contains("最高温")){
                    String surHourMax = smsWarningService.getSurHourMax(smsThreshold.getStation(),smsThreshold.getParam(),smsThreshold.getHour());
                    logger.info("surHourMax->{}",surHourMax);
                    if (Double.parseDouble(surHourMax)>Double.parseDouble(smsThreshold.getThreshold())&&!warningSet.contains(smsThreshold.getId())){
                        content+=smsThreshold.getStationName()+smsThreshold.getName()+"数值"+surHourMax+"，超出阈值"+smsThreshold.getThreshold()+"。";

                        warningSet.add(smsThreshold.getId());
                    }
                }
            }
        }

        //TODO
        if (!"".equals(content)){
            smsWarningService.sendMsg(content);
            logger.info("信息发送成功->{}",content);
        }
    }

    @Scheduled(cron="0 0 6,12,20 * * ?")//每天的6点、12点、20点都执行一次
    public void emptySet(){
        warningSet.clear();
    }

}
